<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
         *  搭建一个服务器 server.js 并提供数据接口 /getData
         *  定义 发送ajax函数，发送ajax请求。返回值是Promise对象
         *  使用async await 获取数据
         */

        function getData() {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('get', 'http://localhost:8080/getData');
                xhr.responseType = 'json';
                xhr.send();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState !== 4) return;
                    let { status } = xhr;
                    if (status >= 200 && status < 300) {
                        resolve(xhr.response);
                    }else{
                        reject(status);
                    }
                }
            })
        }

        (async function(){
            let data = await getData();
            console.log(data);
        })()

    </script>
</body>

</html>